<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      @submit.native.prevent
    >
      <el-form-item label="企业名称" prop="corpName">
        <el-input
          v-model="queryParams.corpName"
          placeholder="请输入企业名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:client:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:client:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="selected.length === 0"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:client:upload']"
          type="success"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="$refs.file.click()"
        >导入</el-button>
        <input ref="file" type="file" style="display: none" @change="handleUpload">
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:client:export']"
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['client:client:upload']"
          type="success"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleDownload"
        >导入模板下载</el-button>
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      ref="table"
      v-loading="loading"
      :data="list"
      @selection-change="(selection) => selected = selection"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="企业名称" prop="corpName" :show-overflow-tooltip="true" />
      <el-table-column label="需求名称" prop="needName" :show-overflow-tooltip="true" />
      <el-table-column label="需求类型">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.custom_need_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="处理人名称" prop="handlerName" />
      <el-table-column label="需求描述" prop="description" />
      <el-table-column label="状态" width="200">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_data_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['client:client:edit']"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['client:client:remove']"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="goDetailPage(scope.row)"
          >详情</el-button> -->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-form-item label="企业名称" prop="corp">
          <el-select
            v-model="form.corp"
            filterable
            remote
            placeholder="请输入关键词查询"
            :remote-method="searchCorp"
            :loading="searchLoading"
          >
            <el-option
              v-for="item in corpList"
              :key="item.id"
              :label="item.name"
              :value="item.corp"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="需求名称" prop="needName">
          <el-input v-model="form.needName" placeholder="请输入需求名称" />
        </el-form-item>
        <el-form-item label="需求类型" prop="type">
          <el-select v-model="form.type" style="width: 240px">
            <el-option
              v-for="dict in dict.type.custom_need_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="处理人" prop="handler">
          <el-select
            v-model="form.handler"
            filterable
            remote
            placeholder="请输入关键词查询"
            :remote-method="searchUser"
            :loading="searchLoading"
          >
            <el-option
              v-for="item in userList"
              :key="item.userId"
              :label="item.userName"
              :value="item.user"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" style="width: 240px">
            <el-option
              v-for="dict in dict.type.sys_data_status"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="需求描述" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入需求内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRequirement, getRequirement, delRequirement, addRequirement, updateRequirement, importRequirement } from '@/api/client/requirement'
import { listClient } from '@/api/client/client'
import { listUser } from '@/api/system/user'

export default {
  name: 'RequirementList',
  dicts: ['custom_need_type', 'sys_data_status'],
  data() {
    return {
      loading: true,
      // 选中数组
      selected: [],
      showSearch: true,
      list: [],
      total: 0,

      // 弹出层标题
      title: '',
      open: false,
      searchLoading: false,
      corpList: [],
      userList: [],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        corpName: undefined
      },

      // 表单参数
      form: {},
      rules: {
        corp: [
          { required: true, message: '企业名称不能为空', trigger: 'blur' }
        ],
        needName: [
          { required: true, message: '需求名称不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '需求类型不能为空', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'blur' }
        ],
        handler: [
          { required: true, message: '处理人不能为空', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '需求描述不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.loading = true
      const query = {
        ...this.queryParams,
        busiType: (this.queryParams.busiType || []).join(',')
      }
      listRequirement(query).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.loading = false
      }
      )
    },
    searchCorp(query) {
      const params = {
        pageNum: 1,
        pageSize: 10,
        name: query
      }
      this.searchLoading = true
      listClient(params).then(response => {
        const data = response.data.records.map(item => ({
          ...item,
          corp: `${item.id}/${item.name}`
        }))
        this.corpList = data
        this.searchLoading = false
      })
    },
    searchUser(query) {
      const params = {
        pageNum: 1,
        pageSize: 10,
        userName: query
      }
      this.searchLoading = true
      listUser(params).then(response => {
        const data = response.rows.map(item => ({
          ...item,
          user: `${item.userId}/${item.userName}`
        }))
        this.userList = data
        this.searchLoading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        certNo: null,
        clientName: undefined,
        busiType: []
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加客户需求'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      getRequirement(row.id).then(response => {
        this.form = {
          ...response.data
        }
        this.form.corp = this.form.corpId + '/' + this.form.corpName
        this.form.handler = this.form.handlerId + '/' + this.form.handlerName
        console.log(this.form)
        this.open = true
        this.title = '修改客户需求'
      })
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          const formData = {
            id: '',
            ...this.form,
            corpId: this.form.corp.split('/')[0],
            corpName: this.form.corp.split('/')[1],
            handlerId: this.form.handler.split('/')[0],
            handlerName: this.form.handler.split('/')[1]
          }
          delete formData.corp
          delete formData.handler
          if (this.form.id) {
            updateRequirement(formData).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addRequirement(formData).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.selected.map(v => v.id)
      this.$modal.confirm(`确认删除 ${row.id ? row.name : '所选'} 数据？`).then(function() {
        return delRequirement(ids)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
        this.$refs.table.clearSelection()
        this.selected = []
      }).catch(() => {})
    },
    // 导入
    async handleUpload(event) {
      const data = new FormData()
      data.append('file', event.target.files[0])
      await importRequirement(data)
      this.getList()
      this.$refs.file.value = null
    },
    // 导出过滤后的企业数据
    handleExport() {
      const query = {
        ...this.queryParams,
        busiType: (this.queryParams.busiType || []).join(',')
      }
      this.download('security/needInfo/export', query, `客户需求信息表_${new Date().getTime()}.xlsx`)
    },
    // 下载模板
    handleDownload() {
      this.download('security/needInfo/importTemplate', {}, `客户需求信息表模板.xlsx`)
    },
    goDetailPage(row) {
      this.$router.push({
        name: 'RequirementDetail',
        params: {
          id: row.id
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.busi-tag + .busi-tag {
  margin-left: 5px;
}
</style>
